package com.huantai.common.util.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.huantai.common.enums.CharsetEnum;
import com.huantai.common.exception.BusinessException;

/**
 * GZIP压缩与解压缩工具
 * 
 * @author Ma Chao
 * @version 2018年7月24日 下午12:05:39
 */
public class GzipUtil {
    private GzipUtil() {}

    /**
     * 按指定的编码格式压缩字符串
     * 
     * @param str 要压缩的字符串
     * @param encoding 编码格式
     * @return
     * @throws IOException
     */
    public static byte[] compress(String str, CharsetEnum encoding) throws IOException {
        if (str == null || str.length() == 0) {
            throw new BusinessException("要解压的数据不能为空！");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip;
        gzip = new GZIPOutputStream(out);
        gzip.write(str.getBytes(encoding.getValue()));
        gzip.close();
        return out.toByteArray();
    }

    /**
     * 使用UTF-8压缩字符串
     * 
     * @param str 要压缩的字符串
     * @return
     * @throws IOException
     */
    public static byte[] compress(String str) throws IOException {
        return compress(str, CharsetEnum.UTF_8);
    }

    /**
     * 解压字节数组
     * 
     * @param bytes
     * @return
     * @throws IOException
     */
    public static byte[] uncompress(byte[] bytes) throws IOException {
        if (bytes == null || bytes.length == 0) {
            throw new BusinessException("要解压的数据不能为空！");
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);

        GZIPInputStream ungzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = ungzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 使用指定的编码格式解压字节数组
     * 
     * @param bytes 要解压的字节数组
     * @param encoding 编码格式
     * @return
     * @throws IOException
     */
    public static String uncompressToString(byte[] bytes, CharsetEnum encoding) throws IOException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        GZIPInputStream ungzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];
        int n;
        while ((n = ungzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }
        return out.toString(encoding.getValue());
    }

    /**
     * 使用UTF-8解压字节数组
     * 
     * @param bytes 要解压的字节数组
     * @return
     * @throws IOException
     */
    public static String uncompressToString(byte[] bytes) throws IOException {
        return uncompressToString(bytes, CharsetEnum.UTF_8);
    }
}
